using System.Collections.ObjectModel;
using System.Net;
using System.Net.WebSockets;
using System.Text;
using System.Windows;
using System.Windows.Threading;

namespace WpfServer
{
    public partial class MainWindow : Window
    {


        public ObservableCollection<WebSocketClient> ConnectedClients { get; } = new();

        private WebSocketServerHelper _serverHelper;

        public MainWindow()
        {
            InitializeComponent();
            DataContext = this;
        }

        private async void BtnStart_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                _serverHelper = new WebSocketServerHelper();
                _serverHelper.ClientConnected += client => Dispatcher.Invoke(() => ConnectedClients.Add(client));
                _serverHelper.ClientDisconnected += id => Dispatcher.Invoke(() => 
                {
                    var item = ConnectedClients.FirstOrDefault(c => c.Id == id);
                    if (item != null) ConnectedClients.Remove(item);
                });
                _serverHelper.Start(int.Parse(txtPort.Text));
                UpdateUI(true);
                LogMessage("WebSocket 服务器已启动");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

 
        private void BtnStop_Click(object sender, RoutedEventArgs e)
        {
            try
            {

                UpdateUI(false);
                LogMessage("WebSocket 服务器已停止");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void UpdateUI(bool isRunning)
        {
            Dispatcher.Invoke(() =>
            {
                btnStart.IsEnabled = !isRunning;
                btnStop.IsEnabled = isRunning;
                txtStatus.Text = isRunning ? "运行中" : "已停止";
            });
        }

        private void LogMessage(string message)
        {
            Dispatcher.Invoke(() =>
            {
                txtLog.AppendText($"{DateTime.Now:HH:mm:ss} {message}\n");
                txtLog.ScrollToEnd();
            });
        }


    }
}